const { body } = require('express-validator')
const User = require('../model/user')
const validate = require("../middleware/validate");

exports.login = [
  validate([
    body('username').notEmpty().withMessage('用户名不能为空'),
    body('password').notEmpty().withMessage('密码不能为空')
  ]),
  validate([
    body('username').custom(async (username, { req }) => {
      const user = await User.findOne({ username })
        .select(['username', 'email', 'bio', 'image'])
      if (!user) {
        return Promise.reject('用户不存在')
      }
      req.user = user
    })
  ])
]
exports.register = validate([
  body('username')
    .notEmpty().withMessage('用户名不能为空')
    .custom(async username => {
      const user = await User.findOne({ username })
      if (user) {
        return Promise.reject('用户名已存在')
      }
    }),
  body('password').notEmpty().withMessage('密码不能为空')
])